package com.demo.persistencia.generica.util;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;


public class HibernateUtil implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private static ApplicationContext contextoSpring;
	
	 public void IniciarContextoSpring() {
			String[] paths = {
					"classpath:/conf/applicationContext-dao.xml",
				    "classpath:/conf/applicationContext-listaHiberXml.xml",
				    "classpath:/conf/applicationContext-compass-base_only_compass.xml",
				    "classpath:/conf/applicationContext-Config.xml"
					};
	        contextoSpring = new ClassPathXmlApplicationContext(paths);
		}
	
	  public  void openSession(){  
	        SessionFactory  sessionFactory = (SessionFactory) contextoSpring.getBean("sessionFactory");  
	        Session session = SessionFactoryUtils.getSession(sessionFactory, true);  
	        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));   
	       
	    }  
	      
	    public   void closeSession(){  
	        SessionFactory  sessionFactory = (SessionFactory) contextoSpring.getBean("sessionFactory");  
	        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);  
	        sessionHolder.getSession().flush();  
	        SessionFactoryUtils.closeSession(sessionHolder.getSession());  
	          
	    }

		public static ApplicationContext getContextoSpring() {
			return contextoSpring;
		}

		public static void setContextoSpring(ApplicationContext contextoSpring) {
			HibernateUtil.contextoSpring = contextoSpring;
		} 
	    
	    
}
